package com.ruantong.dingtalk.ding.openapi;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.ruantong.dingtalk.ding.config.DingProperties;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description:获取token的api
 * @author: jh.chen
 * @time: 2020/11/14 9:34
 */
@Component
@Slf4j
public class GetTokenApi {

    @Autowired
    private DingProperties dingProperties;

    public String getToken() {
        String token = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(dingProperties.getAppKey());
            req.setAppsecret(dingProperties.getAppSecret());
            req.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(req);
            token = response.getAccessToken();
            log.info("GetToken from DingTalk:{}", token);
        } catch (ApiException e) {
            log.error(e.getErrCode(), e.getErrMsg());
        }
        return token;
    }
}
